package org.person.demo.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.person.demo.service.PaymentService;
import org.person.springcloud.models.CommonResult;
import org.person.springcloud.models.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CircleBreakerController {

    public static final String URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/fallback/payment/{id}")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") // 只处理业务异常
//    @SentinelResource(value = "blockException", blockHandler = "blockHandler")  // 只负责sentinel配置违规
    @SentinelResource(value = "fallback",
            fallback = "handlerFallback",
            blockHandler = "blockHandler",
            exceptionsToIgnore = {IllegalArgumentException.class}
    )
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(URL + "/payment/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        } else if (result.getData() == null) {
            throw new NullPointerException("没有对应id数据");
        }
        return result;

    }

    @GetMapping("/consumer/openfeign/payment/{id}")
    public CommonResult<Payment> payment(@PathVariable("id") Long id){
        return paymentService.payment(id);
    }

    public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable throwable) {
        Payment payment = new Payment(id, null);
        return new CommonResult(444, throwable.getMessage(), payment);
    }

    public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e) {
        Payment payment = new Payment(id, null);
        return new CommonResult(445, e.getMessage(), payment);
    }
}
